import { createStore } from 'vuex'

export default createStore({
    state: {
        token: localStorage.getItem('token') || '',
        userInfo: JSON.parse(localStorage.getItem('userInfo')) || null,
        sidebarCollapse: false
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
            localStorage.setItem('token', token)
        },
        SET_USER_INFO(state, userInfo) {
            state.userInfo = { ...userInfo, english: userInfo.english || '' }
            localStorage.setItem('userInfo', JSON.stringify(userInfo))
        },
        TOGGLE_SIDEBAR(state) {
            state.sidebarCollapse = !state.sidebarCollapse
        },
        LOGOUT(state) {
            state.token = ''
            state.userInfo = null
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
        }
    },
    actions: {
        login({ commit }, { token, userInfo }) {
            commit('SET_TOKEN', token)
            commit('SET_USER_INFO', userInfo)
        },
        logout({ commit }) {
            commit('LOGOUT')
        }
    }
})